/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.server.core.communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * This class contains utility methods to wrap the URL fetching mechanism. This should only be used when the
 * response is known to be simple and contains a small number of lines. If it's large, an in place code will
 * be more efficient and flexible
 * @author Sunny Gupta
 *
 */
public class URLFetchService {
  // TODO: Use URLEncode to remove illegal characters before fetching the URL

  private static final char LINE_BREAK = '\n';

  public static String urlGet(String urlString) throws IOException , MalformedURLException {
    StringBuilder result = null;
    BufferedReader reader = null;
    try {
      URL url = new URL(urlString);
      reader = new BufferedReader(new InputStreamReader(url.openStream()));

      result = new StringBuilder();
      String line;

      while ((line = reader.readLine()) != null) {
        result.append(line + LINE_BREAK);
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
    }

    if (result == null) {
      return null;
    } else {
      String val = result.toString();
      int len = val.length() - 1;
      if (val.charAt(len) == LINE_BREAK) {
        // Remove extra line break at the end
        val = val.substring(0, len);
      }

      return val;
    }
  }
  
  public static boolean urlPost(String urlString, String messageString) throws IOException , MalformedURLException {
    String message = URLEncoder.encode(messageString, "UTF-8");
    OutputStreamWriter writer = null;
    boolean success = false;
    HttpURLConnection connection = null;
    try {
      URL url = new URL(urlString);
      connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");

      writer = new OutputStreamWriter(connection.getOutputStream());
      writer.write(message);

      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        success = true;
      }
    } finally {
      writer.close();
    }

    return success;
  }
}
